﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace Z.Nlayer.Utility
{
    public class TString
    {

        // 代码页
        private static Encoding m_encoding = Encoding.GetEncoding("gb2312");

        // 创建实例时,对应的StringBuilder
        private StringBuilder m_strB = new StringBuilder();

        public TString()
        {
        }

        public TString(string value)
        {
            if (value != null)
            {
                this.m_strB.Append(value.ToCharArray());
            }
            return;
        }
        // 返回长度
        public int length
        {
            get
            {
                return this.m_strB.Length;
            }
        }

        // 复制文本
        public void copy(string value)
        {
            int ilen = this.m_strB.Length;
            if (ilen > 0)
            {
                this.m_strB.Remove(0, ilen);
            }
            if (value != null)
            {
                this.m_strB.Append(value.ToCharArray());
            }
            return;
        }

        // 复制文本
        public void copy(TString value)
        {
            int ilen = this.m_strB.Length;
            if (ilen > 0)
            {
                this.m_strB.Remove(0, ilen);
            }
            this.cat(value);
            return;
        }

        // 连接字符串
        public void cat(string value)
        {
            if (value != null)
            {
                this.m_strB.Append(value.ToCharArray());
            }
            return;
        }


        // 连接字符串
        public void cat(TString value)
        {
            int icount = value.m_strB.Length;
            for (int i = 0; i < icount; i++)
            {
                this.m_strB.Append(value.m_strB[i]);
            }
            return;
        }

        // 返回字符串
        public new string ToString()
        {
            return this.m_strB.ToString();
        }

        public string ToString(int startindex, int count)
        {
            string result = "";
            if (this.m_strB.Length - startindex >= count)
            {
                char[] ca = new char[count];
                this.m_strB.CopyTo(startindex, ca, 0, count);
                result = TString.toString(ca);
            }
            else
            {
                count = this.m_strB.Length - startindex;
                if (count > 0)
                {
                    char[] ca = new char[count];
                    this.m_strB.CopyTo(startindex, ca, 0, count);
                    result = TString.toString(ca);
                }
            }
            return result;
        }

        public string Substring(int startindex, int count)
        {
            return this.ToString(startindex, count);
        }

        // 从左向右查找字符串,从0开始计位置
        public int find(string search, bool ignoreCase)
        {
            return TString.find(this.ToString(), search, ignoreCase);
        }

        public static TString operator +(TString left, TString right)
        {
            TString result = new TString();
            result.copy(left);
            result.cat(right);
            return result;
        }

        // 从左边开始,取多少个字符
        public static string leftStr(string value, int ilength)
        {
            string result = "";
            if (value != null && ilength > 0)
            {
                if (value.Length > ilength)
                {
                    result = value.Substring(0, ilength);
                }
                else
                {
                    result = value;
                }
            }
            return result;
        }

        // 从左向右查找字符串,从0开始计位置
        public static int find(string value, string search, bool ignoreCase)
        {
            int result = -1;
            if (string.IsNullOrEmpty(value))
            {// 被查找为空串
            }
            else if (string.IsNullOrEmpty(search))
            {// 无分隔符
            }
            else if (value.Length < search.Length)
            {// 查找串小于分隔符
            }
            else if (value.Length == search.Length && string.Compare(value, search, ignoreCase) == 0)
            {// 全等 
                result = 0;
            }
            else
            {// value比splitStr长
                char[] arrA = ignoreCase ? value.ToLower().ToCharArray() : value.ToCharArray();
                char[] arrStr = ignoreCase ? search.ToLower().ToCharArray() : search.ToCharArray();

                int isearchLen = arrStr.Length;
                int ilen = arrA.Length - arrStr.Length + 1;
                for (int i = 0; i < ilen; i++)
                {
                    if (arrA[i] == arrStr[0])
                    {
                        bool bEqual = true;
                        for (int j = 1; j < isearchLen; j++)
                        {
                            if (arrA[i + j] != arrStr[j])
                            {
                                bEqual = false;
                                break;
                            }
                        }
                        if (bEqual)
                        {
                            result = i;
                            break;
                        }
                    }
                }
            }
            return result;
        }

        // 取指定分隔字串的左边的内容
        public static string leftStr(string value, string splitStr, bool ignoreCase)
        {
            string result = "";
            int ipos = TString.find(value, splitStr, ignoreCase);
            if (ipos != -1)
            {
                result = TString.leftStr(value, ipos);
            }
            else
            {
                result = "";
            }
            return result;
        }

        // 从右边开始,取多少个字符
        public static string rightStr(string value, int ilength)
        {
            string result = "";
            if (value != null && ilength > 0)
            {
                if (value.Length > ilength)
                {
                    result = value.Substring(value.Length - ilength, ilength);
                }
                else
                {
                    result = value;
                }
            }
            return result;
        }

        // 取指定分隔字串的右边的内容
        public static string rightStr(string value, string splitStr, bool ignoreCase)
        {
            string result = "";
            int ipos = TString.find(value, splitStr, ignoreCase);
            if (ipos != -1)
            {
                result = TString.rightStr(value, value.Length - ipos - splitStr.Length);
            }
            else
            {
                result = "";
            }
            return result;
        }

        // 字符串比较,区分大小写
        public static int strcmp(string a, string b)
        {
            return string.Compare(a, b, false);
        }

        // 字符串比较,不分大小写
        public static int strcmpi(string a, string b)
        {
            return string.Compare(a, b, true);
        }

        // 比较两个字符数组,区分大小写
        public static int strcmp(char[] a, char[] b)
        {
            int result = 0;
            int alen = a.Length;
            int blen = b.Length;

            for (int i = 0; result == 0 && i < alen && i < blen; i++)
            {
                if (a[i] < b[i])
                {
                    result = i + 1;
                }
                else if (a[i] < b[i])
                {
                    result = -(i + 1);
                }
            }
            if (result == 0)
            {
                if (alen < blen)
                {
                    result = -(alen + 1);
                }
                else if (alen > blen)
                {
                    result = alen + 1;
                }
            }
            return result;
        }

        // 比较两个字符数组,不分大小写
        public static int strcmpi(char[] a, char[] b)
        {
            int result = 0;
            int alen = a.Length;
            int blen = b.Length;

            for (int i = 0; result == 0 && i < alen && i < blen; i++)
            {
                char a1 = char.ToLower(a[i]);
                char b1 = char.ToLower(b[i]);
                if (a1 < b1)
                {
                    result = i + 1;
                }
                else if (a1 < b1)
                {
                    result = -(i + 1);
                }
            }
            if (result == 0)
            {
                if (alen < blen)
                {
                    result = -(alen + 1);
                }
                else if (alen > blen)
                {
                    result = alen + 1;
                }
            }
            return result;
        }

        // 转换为字符串
        public static string toString(Encoding encoding, byte[] text)
        {
            return encoding.GetString(text);
        }

        // 转换为字符串,gb2312
        public static string toString(byte[] text)
        {
            string result = "";
            try
            {
                result = TString.toString(m_encoding, text);
            }
            catch
            {
            }
            return result;
        }

        // 转换为字符串
        public static string toString(char[] text)
        {
            StringBuilder sbR = new StringBuilder();
            return sbR.Append(text).ToString();
        }

        // 转换为byte数组
        public static byte[] toBytes(Encoding encoding, string text)
        {
            byte[] result = null;
            try
            {
                result = encoding.GetBytes(text);
            }
            catch
            {
            }
            return result;
        }

        // 转换为bytes数组,gb2312
        public static byte[] toBytes(string text)
        {
            byte[] result = null;
            try
            {
                result = TString.toBytes(m_encoding, text);
            }
            catch
            {
            }
            return result;
        }

        // 转换一个十六进制数
        private static byte toHex(byte value)
        {
            byte res = 0;
            value &= 0x0f;
            if (value < 10)
            {
                res = (byte)(value + 48);
            }
            else
            {
                res = (byte)(value + 55);
            }
            return res;
        }

        // 把一个byte数组,转换为一个十六进制字符串
        public static string bytesToHexString(byte[] bytes)
        {
            string result = "";
            if (bytes.Length > 0)
            {
                byte[] bytes2 = new byte[2 * bytes.Length];

                for (int i = 0; i < bytes.Length; i++)
                {
                    bytes2[2 * i + 0] = TString.toHex((byte)(bytes[i] >> 4));
                    bytes2[2 * i + 1] = TString.toHex(bytes[i]);
                }
                result = TString.toString(bytes2);
            }
            return result;
        }

        // 把一个字符串,转换为一个十六进制字符串
        public static string stringToHexString(Encoding encoding, string text)
        {
            return TString.bytesToHexString(TString.toBytes(encoding, text));
        }

        // 把一个字符串,转换为一个十六进制字符串,gb2312
        public static string stringToHexString(string text)
        {
            return TString.bytesToHexString(TString.toBytes(text));
        }

        // 把十六进制数,转换为值
        private static byte hexToByte(byte value)
        {
            byte result = 0;
            if (value >= '0' && value <= '9')
            {
                result = (byte)(value - 48);
            }
            else if (value >= 'A' && value <= 'F')
            {
                result = (byte)(value - 55);
            }
            else if (value >= 'a' && value <= 'f')
            {
                result = (byte)(value - 87);
            }
            return result;
        }

        // 把一个十六进制字符串,转换为byte数组
        public static byte[] hexToBytes(string text)
        {
            byte[] result = null;
            byte[] bText = TString.toBytes(text);
            result = new byte[bText.Length / 2];

            for (int i = 0; i < result.Length; i++)
            {
                result[i] = (byte)((TString.hexToByte(bText[2 * i + 0]) << 4) | TString.hexToByte(bText[2 * i + 1]));
            }

            return result;
        }

        // 还原一个十六进制串
        public static string hexToString(string text)
        {
            return TString.toString(TString.hexToBytes(text));
        }

        /// <summary>
        /// 拆分字符串(string.split),不含空行
        /// </summary>
        /// <param name="str"></param>
        /// <param name="separator"></param>
        /// <returns></returns>
        public List<string> Split(string str, string separator)
        {
            return TString.Split(str, separator, false);

        }

        /// <summary>
        /// 拆分字符串(string.split)
        /// </summary>
        /// <param name="str"></param>
        /// <param name="separator"></param>
        /// <param name="hasEmpty"></param>
        /// <returns></returns>
        public static List<string> Split(string str, string separator, bool hasEmpty)
        {
            List<string> result = new List<string>();

            if (string.IsNullOrEmpty(str))
            {
                return result;
            }
            else if (string.IsNullOrEmpty(separator))
            {// 空分隔串
                result.Add(str);
                return result;
            }

            char[] strSep = separator.ToCharArray();
            string[] str2 = str.Split(strSep);
            foreach (string sItem in str2)
            {
                if (hasEmpty)
                {
                    result.Add(sItem);
                }
                else
                {
                    if (!string.IsNullOrEmpty(sItem))
                    {
                        result.Add(sItem);
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 处理成sql语句字符串(并含首尾引号)
        /// </summary>
        /// <param name="value">字符串</param>
        /// <returns></returns>
        public static string PrepaireSqlString(string value)
        {
            return TString.PrepaireSqlString(value, true);
        }

        /// <summary>
        /// 处理成sql语句字符串
        /// </summary>
        /// <param name="value">字符串</param>
        /// <param name="hasDelimiter">是否包含首尾引号</param>
        /// <returns></returns>
        public static string PrepaireSqlString(string value, bool hasDelimiter)
        {
            if (hasDelimiter)
            {
                if (!string.IsNullOrEmpty(value))
                {
                    return "'" + value.Replace("'", "''") + "'";
                }
                else
                {
                    return "''";
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(value))
                {
                    return value.Replace("'", "''");
                }
                else
                {
                    return "";
                }
            }
        }

        /// <summary>
        /// 比较两个字符串是否一致 忽略大小写
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public static bool Compare2String(string a, string b)
        {
            bool bResult = false;
            if (string.Compare(a, b, true) == 0)
            {
                bResult = true;
            }
            return bResult;
        }

        /// <summary>
        /// 去除HTML标记
        /// </summary>
        /// <param name="Htmlstring">包括HTML的源码 </param>
        /// <returns>已经去除后的文字</returns>
        public static string NoHTML(string Htmlstring)
        {
            //删除脚本
            Htmlstring = Htmlstring.Replace("\r\n", "");
            Htmlstring = Regex.Replace(Htmlstring, @"<script.*?</script>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<style.*?</style>", "", RegexOptions.IgnoreCase);
            //Htmlstring = Regex.Replace(Htmlstring, @"<.+>", "", RegexOptions.IgnoreCase);
            //删除HTML
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])|([\s])+", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "", RegexOptions.IgnoreCase);
            Htmlstring = Htmlstring.Replace("<", "&lt;");
            Htmlstring = Htmlstring.Replace(">", "&gt;");
            //Htmlstring = Htmlstring.Replace("\r\n", "");
            return Htmlstring;
        }
    }
}
